package com.itchen.hospital.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itchen.hospital.exception.CustomException;
import com.itchen.hospital.mapper.DoctorMapper;
import com.itchen.hospital.pojo.Doctor;
import com.itchen.hospital.pojo.Params;
import com.itchen.hospital.service.DoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;

    /**
     * 查询所有医生
     * @return
     */
    @Override
    public List<Doctor> getAll() {
        return doctorMapper.getAll();
    }

    //条件查询
    @Override
    public PageInfo<Doctor> search(Params params) {
        //处理分页
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Doctor> list = doctorMapper.findBySearch(params);
        return PageInfo.of(list);
    }

    //添加
    @Override
    public void add(Doctor doctor) {
        //先查询数据库数据,如果此账号在数据库中已存在，则不能添加
        if (doctorMapper.findByAccount(doctor.getAccount()) != null) {
            throw new CustomException("此账号已存在,无法添加!");
        }
        doctor.setRole("DOCTOR");
        //设置默认密码
        doctor.setPassword("123456");
        doctorMapper.add(doctor);
    }

    //修改
    @Override
    public void update(Doctor doctor) {
        doctorMapper.update(doctor);
    }

    //根据account查询
    @Override
    public Doctor findByAccount(String account) {
        Doctor doctor = doctorMapper.findByAccount(account);
        return doctor;
    }

    //删除
    @Override
    public void delete(String account) {
        doctorMapper.delete(account);
    }

    //批量删除
    @Override
    public void batchDelete(List<Doctor> doctors) {
        doctors.forEach(doctor -> {
            doctorMapper.delete(doctor.getAccount());
        });
    }
}
